Special methods and interface-based type system (Guido Nov 22 21:09:31 2006)
Guido氏がlenメソッドに反対している
There are two bits of "Python rationale" that I'd like to explain first.
First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later).
Human Computer Interactionからの理由(結びついた2つの理由)
2つとも デザインと歴史 FAQ にも採用されている
(a) For some operations, prefix notation just reads better than postfix
(b) When I read code that says len(x) I *know* that it is asking for the length of something.
This tells me two things: the result is an integer, and the argument is some kind of container.
「(len(x)というコードは)結果は整数で、引数はある種のcontainerだと伝えている」
To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len().
「x.len()というコードは、私がすでに、xは標準のlen()メソッドを持つインターフェースを実装している、またはクラスを継承しているある種のコンテナだと知っていなければならない」
混乱の例
mappingを実装していないクラスがget()やkeys()メソッドを持つ
ファイルでないものがwrite()メソッドを持つ
Saying the same thing in another way, I see 'len' as a built-in *operation*.
「言い換えると、(Guido氏は)lenを組み込みの*操作*として見ている」
'def len(self): ...' certainly sounds like you want to demote it to an ordinary method.
「'def len(self): ...'とメソッドにするのは、lenを普通のメソッドに降格したいように聞こえる」
The second bit of Python rationale I promised to explain is the reason why I chose special methods to look __special__ and not merely special.
特殊メソッドの名前にアンダースコアを2つつけるようにした理由(specialでなく__special__)
I was anticipating lots of operations that classes might want to override, some standard (e.g. __add__ or __getitem__), some not so standard (e.g. (略)).
「クラスがひょっとするとoverrideしたいかもしれないたくさんの操作を見越していた」
I didn't want these special operations to use ordinary method names, because then pre-existing classes, or classes written by users without an encyclopedic memory for all the special methods, would be liable to accidentally define operations they didn't mean to implement, with possibly disastrous consequences.
「すべての特殊メソッドに渡る博学な記憶力を持たないユーザによって書かれたクラスが、ありうる悲惨な結果によって、実装することを意図しない操作を誤って定義しがちになるため、特殊な操作には通常のメソッド名を使いたくない」